package com.scau.phr.business.auth.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.scau.phr.business.auth.domain.Constant;
import com.scau.phr.business.auth.domain.Role;
import com.scau.phr.business.auth.domain.Session;
import com.scau.phr.business.auth.service.PowerManager;
import com.scau.phr.business.auth.service.SessionService;
import com.scau.phr.common.domain.ApiResult;
import com.scau.phr.common.exceptions.ErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 在这里进行角色的权限过滤
 * @author yuzhiyi
 * @date 2018/7/29 18:39
 */

public class RoleFilter implements Filter {

	private Logger logger = LoggerFactory.getLogger(RoleFilter.class);
	private SessionService sessionService;
	private  String ERROR_API_RESULT_JSON;

	public RoleFilter(){

	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		ApiResult result = ApiResult.errorOf(ErrorCode.NO_PERMISSION);
		ObjectMapper mapper = new ObjectMapper();
		try {
			ERROR_API_RESULT_JSON = mapper.writeValueAsString(result);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			ERROR_API_RESULT_JSON = "{errorCode:211,message:'',value:{}}";
		}
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		String uri = httpServletRequest.getRequestURI();
		String token = getToken(httpServletRequest);
		Role role = getRole(token);
		if (PowerManager.matchRole(uri,role)){
			chain.doFilter(request,response);
		}else{
			logger.debug("uri:{},token:{},role:{} 权限不足",uri,token,role);
			response.setContentType("application/json;charset=UTF-8");
			response.getWriter().append(ERROR_API_RESULT_JSON).flush();
		}
	}

	@Override
	public void destroy() {

	}

	private String getToken(HttpServletRequest request){
		try{
			String token = request.getParameter(Constant.TOKEN);
			return token;
		}catch (Exception e){
			return null;
		}
	}

	private Role getRole(String token){
		if (token == null){
			return Role.GUEST;
		}
		Session session = sessionService.getSession(token);
		if (session == null){
			return Role.GUEST;
		}
		return session.getRole();
	}

	public SessionService getSessionService() {
		return sessionService;
	}

	public void setSessionService(SessionService sessionService) {
		this.sessionService = sessionService;
	}
}
